#!/usr/bin/env python3

import gt
import os
import vt

"""
    全局变量的定义
"""
#   画布大小
ROW, COL = 15, 60
#   球的属性描述
x, y, x_inc, y_inc, r, color, ch = 3, 3, 1, 1, 3, vt.RED, '@'
#   暂停标志位
pause = False
#   画布创建
canvas = None

"""
    画布创建
"""
#   用列表方式创建画布
def createCanvas(r, c):
    canvas = list(range(r))
    for x in canvas:
        canvas[x] = list(range(c))
    return canvas

"""
    画布初始化
"""
def initCanvas(canvas, row, col):
    for r in range(row):
        for c in range(col):
            if r == 0 or c == 0 or r == row - 1 or c == col - 1:
                canvas[r][c] = "#"  #   画出画布边框范围
            else:
                canvas[r][c] = ' '

    return canvas

"""
    刷新画布
"""
def showCanvas(canvas, row, col, color, ch):
    vt.goto(back=False)

    for r in range(row):
        for c in range(col):
            #  print([canvas[r][c], vt.color(ch, color)][canvas[r][c] == ch],
                    #  end='')
             if canvas[r][c] == ch:
                 vt.color(ch, color, back=False)
             else:
                 print(canvas[r][c], end='')
        print()

"""
    在画布上作画
"""
def draw(canvas, row, col, x, y, r, ch):
    for i in range(y, y + r):
        for j in range(x, x + r):
            if i > ROW - 1 or j > COL - 1 or i < 0 or j < 0: #    限制球的范围
                continue
            canvas[i][j] = ch

"""
    弹球程序的初始化操作
"""
def ball_init(row, col):
    vt.run([vt.SCREEN, vt.HIDE])
    gt.init()
    return createCanvas(row, col)

"""
    弹球程序退出终端还原操作
"""
def ball_exit(row):
    vt.run([vt.goto(row + 2), vt.SHOW])
    gt.exit()
    os._exit(0)

"""
    弹球运动控制
"""
def move():
    global x, y, x_inc, y_inc, color

    if x <= 0 or x + r > COL - 1:
        x_inc *= -1
        color = vt.getColor()

    if y <= 0 or y + r > ROW - 1:
        y_inc *= -1
        color = vt.getColor()

    x += x_inc
    y += y_inc

"""
    弹球动画流程
"""
def ball():
    if pause:
        return

    initCanvas(canvas, ROW, COL)
    draw(canvas, ROW, COL, x, y, r, ch)
    move()
    showCanvas(canvas, ROW, COL, color, ch)

    #   下一次动画显示的延时设置
    gt.run(ball, 0.1)

def keyHandle():
    global color, x_inc, y_inc, pause

    while True:
        ch = gt.get()
        if ch == 'q' or ord(ch) == 27:  #   按q 或 ESC 键退出
            break
        elif ch == 'c': #   颜色改变控制
            color = vt.getColor()
        elif ch == 'w': #   向上运动控制
            y_inc = -1
        elif ch == 's': #   向下运动控制
            y_inc = 1
        elif ch == 'a': #   向左运动控制
            x_inc = -1
        elif ch == 'd': #   向右运动控制
            x_inc = 1
        elif ch == ' ': #   空格暂停或继续
            pause = not pause
            gt.run(ball)

if __name__ == '__main__':
    #  vt.color("hello", color, back=False)
    #  exit(0)
    #  ball_exit(ROW)
    canvas = ball_init(ROW, COL)
    #  ball()
    #  ball_exit(ROW)
    gt.run(ball)
    keyHandle()
    ball_exit(ROW)
